// 无障碍插件入口文件
// 用于全局注册无障碍功能，集成所有无障碍相关组件和服务

import { createApp } from 'vue';
import AccessibilityService from './AccessibilityService';
import { accessibilityUtils, ARIA_ROLES, ARIA_ATTRIBUTES, KEY_CODES } from '../../utils/accessibilityUtils';

// 无障碍指令 - 为元素添加ARIA属性
const AriaDirective = {
  mounted(el, binding) {
    const { value = {}, modifiers } = binding;
    
    // 设置角色
    if (modifiers.role) {
      el.setAttribute('role', modifiers.role);
    }
    
    // 设置ARIA属性
    Object.entries(value).forEach(([key, val]) => {
      const ariaKey = key.startsWith('aria-') ? key : `aria-${key}`;
      if (val === null || val === undefined || val === false) {
        el.removeAttribute(ariaKey);
      } else {
        el.setAttribute(ariaKey, val.toString());
      }
    });
  },
  
  updated(el, binding) {
    // 更新ARIA属性
    const { value = {}, oldValue } = binding;
    
    // 如果值没有变化，不进行更新
    if (JSON.stringify(value) === JSON.stringify(oldValue)) return;
    
    // 移除旧的属性
    Object.keys(oldValue || {}).forEach(key => {
      const ariaKey = key.startsWith('aria-') ? key : `aria-${key}`;
      el.removeAttribute(ariaKey);
    });
    
    // 设置新的属性
    Object.entries(value).forEach(([key, val]) => {
      const ariaKey = key.startsWith('aria-') ? key : `aria-${key}`;
      if (val === null || val === undefined || val === false) {
        el.removeAttribute(ariaKey);
      } else {
        el.setAttribute(ariaKey, val.toString());
      }
    });
  },
  
  unmounted(el, binding) {
    // 清理ARIA属性
    const { value = {} } = binding;
    
    Object.keys(value).forEach(key => {
      const ariaKey = key.startsWith('aria-') ? key : `aria-${key}`;
      el.removeAttribute(ariaKey);
    });
    
    // 移除角色
    if (binding.modifiers.role) {
      el.removeAttribute('role');
    }
  }
};

// 无障碍指令 - 键盘导航
const KeyboardNavDirective = {
  mounted(el, binding) {
    const { value = {} } = binding;
    const handlers = {};
    
    // 注册键盘事件处理函数
    Object.entries(value).forEach(([key, handler]) => {
      if (typeof handler === 'function') {
        handlers[key.toLowerCase()] = handler;
      }
    });
    
    // 存储处理函数到元素上
    el._keyboardHandlers = handlers;
    
    // 添加键盘事件监听
    el._keyboardListener = (event) => {
      const key = event.key.toLowerCase();
      const handler = handlers[key];
      
      if (handler) {
        // 阻止默认行为
        event.preventDefault();
        event.stopPropagation();
        
        // 执行处理函数
        handler(event);
      }
    };
    
    el.addEventListener('keydown', el._keyboardListener);
    
    // 确保元素可聚焦
    if (!el.hasAttribute('tabindex')) {
      el.setAttribute('tabindex', '0');
    }
  },
  
  updated(el, binding) {
    // 更新键盘处理函数
    const { value = {} } = binding;
    const handlers = {};
    
    Object.entries(value).forEach(([key, handler]) => {
      if (typeof handler === 'function') {
        handlers[key.toLowerCase()] = handler;
      }
    });
    
    el._keyboardHandlers = handlers;
  },
  
  unmounted(el) {
    // 移除事件监听
    if (el._keyboardListener) {
      el.removeEventListener('keydown', el._keyboardListener);
      delete el._keyboardListener;
    }
    
    // 清理处理函数
    if (el._keyboardHandlers) {
      delete el._keyboardHandlers;
    }
  }
};

// 无障碍指令 - 焦点陷阱
const FocusTrapDirective = {
  mounted(el, binding) {
    const { value = true } = binding;
    
    if (!value) return;
    
    // 存储焦点陷阱控制器
    el._focusTrap = accessibilityUtils.trapFocus(el);
    
    // 监听元素可见性变化
    el._visibilityObserver = new MutationObserver((mutations) => {
      mutations.forEach(mutation => {
        if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
          const isVisible = el.style.display !== 'none' && el.style.visibility !== 'hidden';
          
          if (isVisible && !el._focusTrapActive) {
            el._focusTrapController = el._focusTrap.activate();
            el._focusTrapActive = true;
          } else if (!isVisible && el._focusTrapActive && el._focusTrapController) {
            el._focusTrapController.deactivate();
            el._focusTrapActive = false;
          }
        }
      });
    });
    
    el._visibilityObserver.observe(el, { attributes: true });
    
    // 如果元素当前可见，激活焦点陷阱
    const isVisible = el.style.display !== 'none' && el.style.visibility !== 'hidden';
    if (isVisible) {
      el._focusTrapController = el._focusTrap.activate();
      el._focusTrapActive = true;
    }
  },
  
  updated(el, binding) {
    // 更新焦点陷阱状态
    const { value = true } = binding;
    
    if (!value && el._focusTrapActive && el._focusTrapController) {
      el._focusTrapController.deactivate();
      el._focusTrapActive = false;
    } else if (value && !el._focusTrapActive && el._focusTrap) {
      el._focusTrapController = el._focusTrap.activate();
      el._focusTrapActive = true;
    }
  },
  
  unmounted(el) {
    // 停用焦点陷阱
    if (el._focusTrapActive && el._focusTrapController) {
      el._focusTrapController.deactivate();
    }
    
    // 断开观察器
    if (el._visibilityObserver) {
      el._visibilityObserver.disconnect();
      delete el._visibilityObserver;
    }
    
    // 清理引用
    if (el._focusTrap) {
      delete el._focusTrap;
    }
    
    if (el._focusTrapController) {
      delete el._focusTrapController;
    }
  }
};

// 无障碍指令 - 实时区域
const LiveRegionDirective = {
  mounted(el, binding) {
    const { value = {}, modifiers } = binding;
    
    // 设置实时区域属性
    el.setAttribute('aria-live', modifiers.assertive ? 'assertive' : 'polite');
    el.setAttribute('aria-atomic', value.atomic ? 'true' : 'false');
    
    if (value.relevant) {
      el.setAttribute('aria-relevant', value.relevant);
    }
    
    // 应用隐藏样式（如果需要）
    if (modifiers.hidden) {
      Object.assign(el.style, {
        position: 'absolute',
        width: '1px',
        height: '1px',
        margin: '-1px',
        padding: '0',
        border: '0',
        overflow: 'hidden',
        clip: 'rect(0, 0, 0, 0)',
        whiteSpace: 'nowrap'
      });
    }
  }
};

// 无障碍插件
const AccessibilityPlugin = {
  install(app, options = {}) {
    // 初始化无障碍服务
    const accessibilityService = new AccessibilityService(options);
    
    // 将无障碍服务注入到Vue应用中
    app.provide('accessibilityService', accessibilityService);
    
    // 将工具方法挂载到全局属性
    app.config.globalProperties.$accessibility = {
      utils: accessibilityUtils,
      service: accessibilityService,
      roles: ARIA_ROLES,
      attributes: ARIA_ATTRIBUTES,
      keyCodes: KEY_CODES
    };
    
    // 注册全局指令
    app.directive('aria', AriaDirective);
    app.directive('keyboard', KeyboardNavDirective);
    app.directive('focus-trap', FocusTrapDirective);
    app.directive('live-region', LiveRegionDirective);
    
    // 添加全局混入
    app.mixin({
      created() {
        // 组件创建时的无障碍初始化
        if (this.$options.accessibility) {
          this.$accessibility.initComponent(this, this.$options.accessibility);
        }
      },
      
      mounted() {
        // 组件挂载后的无障碍处理
        if (this._accessibilityHandlers) {
          this._accessibilityHandlers.forEach(handler => {
            handler();
          });
        }
      },
      
      beforeUnmount() {
        // 组件卸载前的清理
        if (this._accessibilityCleanup) {
          this._accessibilityCleanup.forEach(cleanup => {
            cleanup();
          });
        }
      }
    });
    
    // 添加全局样式类
    if (options.autoApplyStyles !== false) {
      // 应用高对比度模式
      if (accessibilityService.isHighContrastEnabled()) {
        document.documentElement.classList.add('high-contrast');
      }
      
      // 应用减少动画模式
      if (accessibilityService.isReducedMotionEnabled()) {
        document.documentElement.classList.add('reduced-motion');
      }
      
      // 应用大字体模式
      if (accessibilityService.isLargeTextEnabled()) {
        document.documentElement.classList.add('large-text');
      }
    }
    
    // 监听无障碍设置变化
    accessibilityService.on('configChanged', (config) => {
      // 更新全局样式类
      if (options.autoApplyStyles !== false) {
        document.documentElement.classList.toggle('high-contrast', config.highContrast);
        document.documentElement.classList.toggle('reduced-motion', config.reduceMotion);
        document.documentElement.classList.toggle('large-text', config.largeText);
      }
      
      // 通知所有组件配置已更改
      app.config.globalProperties.$emit('accessibility:configChanged', config);
    });
    
    // 添加无障碍帮助功能
    window.addEventListener('keydown', (event) => {
      // F1 键打开无障碍帮助
      if (event.key === 'F1') {
        event.preventDefault();
        event.stopPropagation();
        
        // 显示无障碍帮助
        const helpInfo = accessibilityUtils.getAccessibilityHelp();
        console.log('无障碍帮助:', helpInfo);
        
        // 如果应用提供了帮助组件，可以在这里打开
        if (options.helpComponent) {
          options.helpComponent.show(helpInfo);
        }
      }
    });
    
    // 添加无障碍跳过导航链接
    if (options.skipLink !== false) {
      const skipLink = document.createElement('a');
      skipLink.href = '#main-content';
      skipLink.className = 'skip-link';
      skipLink.textContent = '跳过导航，直接到内容';
      document.body.prepend(skipLink);
    }
    
    // 导出插件API
    return {
      accessibilityService,
      accessibilityUtils,
      installDirectives: () => {
        // 手动安装指令的方法
        app.directive('aria', AriaDirective);
        app.directive('keyboard', KeyboardNavDirective);
        app.directive('focus-trap', FocusTrapDirective);
        app.directive('live-region', LiveRegionDirective);
      },
      uninstall: () => {
        // 清理插件
        accessibilityService.destroy();
        
        // 移除全局事件监听器
        window.removeEventListener('keydown', this._keydownHandler);
        
        // 移除样式类
        document.documentElement.classList.remove('high-contrast', 'reduced-motion', 'large-text');
        
        // 移除跳过导航链接
        const skipLink = document.querySelector('.skip-link');
        if (skipLink) {
          skipLink.remove();
        }
      }
    };
  }
};

// 辅助函数
function createAccessibilityPlugin(options = {}) {
  return {
    install: (app) => AccessibilityPlugin.install(app, options)
  };
}

// 导出默认插件
export default AccessibilityPlugin;

// 导出工厂函数
export { createAccessibilityPlugin };

// 导出工具和指令
export { 
  AriaDirective,
  KeyboardNavDirective,
  FocusTrapDirective,
  LiveRegionDirective,
  accessibilityUtils,
  ARIA_ROLES,
  ARIA_ATTRIBUTES,
  KEY_CODES
};